import * as signalR from '@microsoft/signalr'
// 确保引入 HttpTransportType
const { HubConnectionBuilder, HttpTransportType } = signalR
class SignalRService {
    constructor() {
        this.connection = null
        this.retryCount = 0
        this.maxRetryCount = 5
      }
    
      startConnection = async () => {
        try {
          this.connection = new signalR.HubConnectionBuilder()
            .withUrl('http://101.201.64.180:8182/hub', {
              skipNegotiation: true,
              transport: signalR.HttpTransportType.WebSockets,
              accessTokenFactory: () => '123456' // 如果有token验证
            })
            .configureLogging(signalR.LogLevel.Debug)
            .withAutomaticReconnect([0, 2000, 5000, 10000, 30000])
            .build()
    
          this.connection.onclose(async () => {
            if (this.retryCount < this.maxRetryCount) {
              this.retryCount++
              setTimeout(() => this.startConnection(), 5000)
            }
          })
    
          await this.connection.start()
          this.retryCount = 0
          //console.log('SignalR 连接成功')
        } catch (err) {
          console.error('SignalR 连接失败:', err)
          if (this.retryCount < this.maxRetryCount) {
            this.retryCount++
            setTimeout(() => this.startConnection(), 5000)
          }
        }
      }
  
    // 添加连接状态检查方法
    isConnected() {
      return this.connection && this.connection.state === signalR.HubConnectionState.Connected
    }
  
    // 修改发送消息方法
    sendMessage = async (methodName, ...args) => {
      if (!this.isConnected()) {
        throw new Error('无法发送消息，连接未就绪')
      }
      return this.connection.invoke(methodName, ...args)
    }
  }

export default new SignalRService()